/**
 * 将十六进制颜色转换为RGB格式
 * @param hex 十六进制颜色
 * @returns RGB格式字符串
 */
export function hexToRgb(hex: string): string {
  let r = 0, g = 0, b = 0;
  
  // 检查格式并提取RGB值
  if (hex.length === 4) { // #RGB
    r = parseInt(hex[1] + hex[1], 16);
    g = parseInt(hex[2] + hex[2], 16);
    b = parseInt(hex[3] + hex[3], 16);
  } else if (hex.length === 7) { // #RRGGBB
    r = parseInt(hex.substring(1, 3), 16);
    g = parseInt(hex.substring(3, 5), 16);
    b = parseInt(hex.substring(5, 7), 16);
  }
  
  return `${r},${g},${b}`;
}

/**
 * 将颜色变暗或变亮
 * @param color 十六进制颜色
 * @param percent 变化百分比（负值变暗，正值变亮）
 * @returns 处理后的十六进制颜色
 */
export function shadeColor(color: string, percent: number): string {
  let R = parseInt(color.substring(1, 3), 16);
  let G = parseInt(color.substring(3, 5), 16);
  let B = parseInt(color.substring(5, 7), 16);

  R = parseInt(String(R * (100 + percent) / 100));
  G = parseInt(String(G * (100 + percent) / 100));
  B = parseInt(String(B * (100 + percent) / 100));

  R = (R < 255) ? R : 255;
  G = (G < 255) ? G : 255;
  B = (B < 255) ? B : 255;

  R = Math.round(R);
  G = Math.round(G);
  B = Math.round(B);

  const RR = ((R.toString(16).length === 1) ? "0" + R.toString(16) : R.toString(16));
  const GG = ((G.toString(16).length === 1) ? "0" + G.toString(16) : G.toString(16));
  const BB = ((B.toString(16).length === 1) ? "0" + B.toString(16) : B.toString(16));

  return "#" + RR + GG + BB;
}

/**
 * 创建一个DOM元素
 * @param tag 标签名
 * @param attributes 属性对象
 * @param children 子元素
 * @returns HTMLElement
 */
export function createElement(
  tag: string,
  attributes: Record<string, any> = {},
  children: (HTMLElement | string)[] = []
): HTMLElement {
  const element = document.createElement(tag);

  // 设置属性
  Object.entries(attributes).forEach(([key, value]) => {
    if (key === 'className') {
      element.className = value;
    } else if (key === 'style' && typeof value === 'object') {
      Object.entries(value).forEach(([prop, val]) => {
        (element.style as any)[prop] = val;
      });
    } else if (key.startsWith('on') && typeof value === 'function') {
      const eventType = key.substring(2).toLowerCase();
      element.addEventListener(eventType, value);
    } else {
      element.setAttribute(key, value);
    }
  });

  // 添加子元素
  children.forEach(child => {
    if (typeof child === 'string') {
      element.appendChild(document.createTextNode(child));
    } else {
      element.appendChild(child);
    }
  });

  return element;
}

/**
 * 格式化数字为两位数字符串
 * @param num 数字
 * @returns 格式化后的字符串
 */
export function formatNumber(num: number): string {
  return String(num).padStart(2, '0');
}

/**
 * 检测是否为移动设备
 * @returns boolean
 */
export function isMobileDevice(): boolean {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}

/**
 * 检测系统是否为暗色模式
 * @returns boolean
 */
export function isSystemDarkMode(): boolean {
  return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
}

/**
 * 格式化时间为 MM:SS 格式
 * @param seconds 秒数
 * @returns string
 */
export function formatTime(seconds: number): string {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}

/**
 * 渲染模板字符串
 * @param template 模板字符串
 * @param data 数据对象
 * @returns string
 */
export function renderTemplate(template: string, data: Record<string, any> = {}): string {
  return template.replace(/\{\{([^}]+)\}\}/g, (_, key) => {
    return data[key.trim()] !== undefined ? data[key.trim()] : '';
  });
}

/**
 * 验证钱包地址格式
 * @param address 钱包地址
 * @returns boolean
 */
export function isValidWalletAddress(address: string): boolean {
  return /^0x[a-fA-F0-9]{40}$/.test(address);
}

/**
 * 去抖函数
 * @param func 函数
 * @param wait 等待时间
 * @returns 去抖后的函数
 */
export function debounce<T extends (...args: any[]) => any>(
  func: T,
  wait: number
): (...args: Parameters<T>) => void {
  let timeout: number | null = null;
  return function(...args: Parameters<T>) {
    if (timeout !== null) {
      clearTimeout(timeout);
    }
    timeout = window.setTimeout(() => {
      func(...args);
    }, wait);
  };
}

/**
 * 动态加载CSS样式
 * @param css CSS样式内容
 * @returns style元素
 */
export function injectCSS(css: string): HTMLStyleElement {
  const style = document.createElement('style');
  style.textContent = css;
  document.head.appendChild(style);
  return style;
}

/**
 * 检查值是否为对象
 * @param item 要检查的值
 * @returns 是否为对象
 */
function isObject(item: any): boolean {
  return (item && typeof item === 'object' && !Array.isArray(item));
}

/**
 * 深度合并对象
 * @param target 目标对象
 * @param source 源对象
 * @returns 合并后的对象
 */
export function deepMerge<T extends Record<string, any>>(target: T, source: Partial<T>): T {
  const output = { ...target } as T;
  
  if (isObject(target) && isObject(source)) {
    Object.keys(source).forEach(key => {
      const sourceValue = source[key as keyof typeof source];
      
      if (isObject(sourceValue) && key in target) {
        const k = key as keyof T;
        output[k] = deepMerge(target[k], sourceValue as any) as any;
      } else {
        const k = key as keyof T;
        output[k] = sourceValue as any;
      }
    });
  }
  
  return output;
} 